﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace app
{
    static class Server
    {
        static UdpClient client;

        static IPEndPoint localEndPoint = null;

        static Thread thread;

        internal static void Start()
        {
            Configure();

            thread = new Thread(new ThreadStart(StartReceiving));

            thread.Start();
        }

        internal static void Stop()
        {
            thread.Abort();
        }

        static void Configure()
        {
            localEndPoint = new IPEndPoint(IPAddress.Any, Parameters.port);

            client = new UdpClient();

            client.Client.ExclusiveAddressUse = false;

            client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

            client.Client.Bind(localEndPoint);
        }

        static void StartReceiving()
        {
            IPEndPoint remoteEndPoint = null;

            byte[] buffer = null;

            try
            {
                buffer = client.Receive(ref remoteEndPoint);
            }
            catch { }

            if (remoteEndPoint != null)
                ThreadPool.QueueUserWorkItem(new WaitCallback(Response.Process), new ThreadStartParams { RemoteEndPoint = remoteEndPoint, Request = buffer });

            StartReceiving();
        }

        internal class ThreadStartParams
        {
            public IPEndPoint RemoteEndPoint;

            public byte[] Request;
        }
    }
}

